package com.csproj.siiat.base.common.util;

import com.csproj.siiat.base.common.exception.BaseAppException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * ==================================================
 * 创建人：wangjf
 * 创建时间：2017/12/13
 * ==================================================
 * 类说明：
 * <p/>
 * ==================================================
 *
 * @version 1.0 2017/12/13
 */
public class FileUtils {

    /**
     * 上传文件获得文件名
     *
     * @param request
     * @param file
     * @param bucketDir
     * @return
     * @autor
     * @date 17-4-10.
     */
    public static String excelUpload(HttpServletRequest request, MultipartFile file, String bucketDir) {
        String fileDir = PathUtils.getUploadPath(request, bucketDir);
        File dir = new File(fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String name = file.getOriginalFilename();
        String fileName = name.substring(0, name.lastIndexOf(".")) +  name.substring(name.lastIndexOf("."));
        String filePath = fileDir.concat("/" + fileName);
        File filePre = new File(filePath);
        int i = 1;
        //防止重名
        while (filePre.exists()) {
            String newFileName = filePre.getName();
            String preFileName = "";
            if (i == 1) {
                preFileName = newFileName.substring(0, newFileName.lastIndexOf(".")) + "_" + 1;
            } else {
                preFileName = newFileName.substring(0, newFileName.lastIndexOf(".") - 2) + "_" + i;
            }
            String extion = newFileName.substring(newFileName.lastIndexOf("."));
            fileName = preFileName + extion;
            filePath = fileDir.concat("/" + fileName);
            filePre = new File(filePath);
            i++;
        }
        try {
            file.transferTo(filePre);
        } catch (IOException e) {
            if (filePre.length() == 0) {
                throw new BaseAppException(false, "上传失败!");
            } else {
                throw new BaseAppException(false, "上传失败!");
            }

        }
        return filePath;
    }
    /**
     * 根据路径获取文件夹下的所有文件路径
     */
    public static List<String> getFileUrl(String url, String path) {
        File f = new File(path);
        if (!f.exists()) {
            return new ArrayList<>();
        }
        File fa[] = f.listFiles();
        List<String> result = new ArrayList<>();
        for (int i = 0; i < fa.length; i++) {
            if (fa[i].isFile()){
                File fs = fa[i];
                result.add(url+"/"+fs.getName());
            }
        }
        return result;
    }
}
